<?php
namespace Weixin\Controller;
use Think\Controller;
use Weixin\ORG\Jssdk;
class OrderController extends BaseController {
    //订单进入页面
    //status = 9 ; 已完成订单列表  status = 1-8,10-14 ; 未完成订单列表
    //complete = 1 ; 没有订单信息  complete = 2 ; 有订单信息
    //style = 0 ;跳转空页面   style = 1 ; 跳转有订单的页面
    //pages 跳转的页面参数 ；用于区分甲方、乙方
    public function index(){
        !empty(I('complete')) ? $complete = I('complete') : $complete = 1;
        if($_SESSION['role'] == 'repair_user' || $_SESSION['role'] == 'repair_agency'){
            $where['partyb_role'] = session('role');
            $where['partyb_id'] = $_SESSION['user']['id'];
        }elseif($_SESSION['role'] == 'hospital' || $_SESSION['role'] == 'device_firms'){
            $where['partya_role'] = session('role');
            $where['partya_id'] = $_SESSION['user']['id'];
        }
        if($complete == 1){
            $where['status'] = 9;
        }else{
            $where['status'] = array("not in",'9,30');
        }
        $list = M('indent')->where($where)->order("order_num desc")->select();
        if(empty($list)){
            //展示空的页面
            $this->assign("style",0)->assign("complete",$complete)->display(I('pages'));
        }else{
            //展示订单列表
            foreach ($list as $k => $v) {
                $list[$k]['machine_type'] = M('device_type')->where('id ='.$list[$k]['machine_type'])->getField('name');
            }
            $this->assign("style",1)->assign("complete",$complete)->assign("list",$list)->display(I('pages'));
        }	
    }
    //查看订单
    //status = 9 ; 已完成订单列表  status = 1-8,10-14 ; 未完成订单列表
    //id 订单id
    //type 跳转的页面参数 ；用于区分甲方、乙方
    public function order_detail($id,$type,$complete){
        $jssdk = new Jssdk(C('APP_ID'), C('APP_SECRET'));
        $signPackage = $jssdk->getSignPackage();
        !empty(I('id'))? $id = I('id') : $id;
        !empty(I('type'))? $type = I('type') : $type;
        !empty(I('complete'))? $complete = I('complete') : $complete;
        $list = M('indent')->where("id=".$id)->find();
        $list['machine_type'] = M('device_type')->where("id =".$list['machine_type'])->getField("name");
        $_SESSION['indent_id'] = $id;
	    $_SESSION['order_num'] = $list['order_num'];
	    $_SESSION['money'] = $list["money"];
        if($complete == 1){
            //查看完成订单详情（甲方|乙方）
            $this->assign("list",$list)->display($type.'_finish');
        }else{
            //查看未完成订单详情（甲方|乙方）
            
            $this->assign('signPackage',$signPackage);
            $this->assign("list",$list)->display($type.'_unfinish');
        }  
    }
    public function new_pay(){
    	$money = session("money") * 100;
    	//全局引入微信支付类
        Vendor('Wxpay.lib.WxPayPubHelper');
        //使用jsapi接口
        $jsApi = new \JsApi_pub();
        //=========步骤1：网页授权获取用户openid============
        //通过code获得openid
        /*if (!isset($_GET['code']))
        {
            //触发微信返回code码
            $url = $jsApi->createOauthUrlForCode($this->fromurl);
            Header("Location: $url");
        }else
        {
            //获取code码，以获取openid
            $code = $_GET['code'];
            $jsApi->setCode($code);
            $openid = $jsApi->getOpenId();
        }
        */
        //=========步骤2：使用统一支付接口，获取prepay_id============
        //使用统一支付接口
        $unifiedOrder = new \UnifiedOrder_pub();
        $unifiedOrder->setParameter("openid",$_SESSION['user']['openid']);//商品描述
        //$type = M('rescue')->where(array('id'=>$_SESSION['pay_id']))->getField('typeing');
        $unifiedOrder->setParameter("body",'医维通');//商品描述
        //自定义订单号，此处仅作举例
        $unifiedOrder->setParameter("out_trade_no",session('order_num'));//商户订单号
        $unifiedOrder->setParameter("total_fee",$money);//总金额
        $unifiedOrder->setParameter("notify_url","http://www.alywt.com/index.php/weixin/order/notify");//通知地址
        $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
        $prepay_id = $unifiedOrder->getPrepayId();
        //=========步骤3：使用jsapi调起支付============
        $jsApi->setPrepayId($prepay_id);
        $jsApiParameters = $jsApi->getParameters();
        $this->assign('jsApiParameters',$jsApiParameters);
        $this->display();
    }
    //JSAPI支付通知
		public function notify(){
				//使用通用通知接口
				//全局引入微信支付类
				Vendor('Wxpay.lib.WxPayPubHelper');
				//$logHandler= new CLogFileHandler("/Public/Weixin/".date('Y-m-d').'.log');
				//$log = Log::Init($logHandler, 15);
				M("huidiao")->where("id=1")->setInc('sum'); 
				$notify = new \Notify_pub();
			    //var_dump($notify);
				//存储微信的回调
				//$xml = file_get_contents("php://input");
				$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
				$notify->saveData($xml);
				$array_data=$notify->data;
				$this->set_php_file("weixin_xml.php", json_encode($array_data));
				//验证签名，并回应微信。
				//对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
				//微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
				//尽可能提高通知的成功率，但微信不保证通知最终能成功。
				$result['return_code'] = 'SUCCESS';
				$result['return_msg'] = $msg;
				$result['sign'] = $this->MakeSign($result);		
				$returnXml = $notify->returnXml($result);
				echo $returnXml;
				//==商户根据实际情况设置相应的处理流程，此处仅作举例=======
				//以log文件形式记录回调信息
				//$log_ = new Log_();
				$log_name= __ROOT__."/Public/Weixin/notify_url.log";//log文件路径
				log_result($log_name,"【接收到的notify通知】:\n".$xml."\n");
				if($notify->checkSign() == TRUE){
					if ($notify->data["return_code"] == "FAIL") {
						//此处应该更新一下订单状态，商户自行增删操作
						log_result($log_name,"【通信出错】:\n".$xml."\n");
					}
					elseif($notify->data["result_code"] == "FAIL"){
						//此处应该更新一下订单状态，商户自行增删操作
						log_result($log_name,"【业务出错】:\n".$xml."\n");
					}
					else{
						//此处应该更新一下订单状态，商户自行增删操作
						log_result($log_name,"【支付成功】:\n".$xml."\n");
					}
					//商户自行增加处理流程,
					//例如：更新订单状态
					//例如：数据库操作
					//例如：推送支付完成信息
				}
		}
		//支付成功改变状态
		public function checkStatus(){
			$id = session("indent_id");
			$data["id"] = $id;
			$data["status"] = 4;
			$data['pay_code'] = 2;
			$data["status4_time"] = date("Y-m-d H:i:s");
			$list = M('indent')->save($data);
			unset($_SESSION["money"]);
            unset($_SESSION["repair_type"]);
			$this->order_detail($id,"ordera_detail",2);
		}
    //接单|派单
    public function receive(){
        //甲方派单(填写维修信息) 
        if($_SESSION['role'] == 'hospital' || $_SESSION['role'] == 'device_firms'){
            if(IS_POST){
                $data = I('post.');
                $where['create_time'] = array('like','%'.date('Y-m-d').'%');
                $num = M('indent')->where($where)->count();
                $data['order_num'] = "YWT".substr(date('Ymd'),2).($num+1);
                $data['partya_role'] = session('role');
                $data['partya_id'] = $_SESSION['user']['id'];
                $data['create_time'] = date("Y-m-d H:i:s");
                $data['status'] = 1;
                $res = M('send_agreement')->add($data);
                if($res){
                    $where['order_num'] = $data['order_num'];
                    $where['partya_role'] = session('role');
                    $where['partya_id'] = $_SESSION['user']['id'];
                    $where['create_time'] = date("Y-m-d H:i:s");
                    $where['status'] = 1;
                    $where['machine_type'] = I('machine_type');
                    $where['machine_name'] = I('machine_name');
                    $where['machine_model'] = I('machine_model');
                    $where['machine_address'] = I('machine_address');
                    $result = M('indent')->add($where);
                    if($result){
                        $this->success("提交成功",U('Order/ordera_send',array('order_num'=>$where['order_num'])));
                    }else{
                        $this->error("提交派工协议失败",U('Order/receive'));
                    }
                }else{
                    $this->error("提交派工协议失败，请重新填写提交",U('Order/receive'));
                }    
            }else{
                $province = M('area')->where('type=1')->select();
                $list = M('device_type')->select();
                $this->assign("list",$list)->assign('province',$province)->display('ordera_receive');
            }
        }elseif($_SESSION['role'] == 'repair_user' || $_SESSION['role'] == 'repair_agency'){
        //乙方接单(筛选甲方沟通人员)
            $data['partyb_role'] = session('role');
            $data['partyb_id'] = $_SESSION['user']['id'];
            $data['status'] = array("in",'2,3');
            $list = M("send_agreement")->where($data)->select();
            foreach ($list as $k => $v) {
                $list[$k]['machine_type'] = M('device_type')->where("id =".$list[$k]['machine_type'])->getField("name"); 
                $list[$k]['avatar'] = M($v['partya_role'])->where('id='.$v['partya_id'])->getField('avatar');
            }
            $this->assign("list",$list)->display('orderb_receive');
        }
    }

    //甲方筛选沟通人员 （换一批） 
    public function ordera_send(){
          $data = M('send_agreement')->where("order_num ='".I('order_num')."'")->field('machine_type,provinceid,cityid,countryid')->find();
        $listn = M()->query("SELECT id,name,avatar from y_repair_user where FIND_IN_SET"."(".$data['machine_type'].","."adept_device) and status=1 and cityid=".$data['cityid'] . " order  by  rand() limit 4");
        $num = 4 - count($listn);
        if($num != 0){
            $ids_arr = array();
            if(!empty($listn)){
                foreach ($listn as $key => $value) {
                    $ids_arr[] = $value['id'];
                }
                $ids = implode($ids_arr,',');
            }else{
                $ids = 0;
            }
            $listy = M()->query("SELECT id,name,avatar from y_repair_user where FIND_IN_SET"."(".$data['machine_type'].","."adept_device) and status=1 and id not in (".$ids.") order  by  rand() limit ".$num);
        }
        $infon = M()->query("SELECT id,head_name from y_repair_agency where FIND_IN_SET" . "(".$data['machine_type'].",".
            "adept_device) and status=1 and cityid=".$data['cityid'] . " order by rand() limit 1");
        
        $tag = 1 - count($infon);
        if($tag != 0){
            $infoy = M()->query("SELECT id,head_name from y_repair_agency where FIND_IN_SET" . "(".$data['machine_type'].",".
            "adept_device) and status=1 order by rand() limit 1");
        }
        $this->assign("listn",$listn)->assign('listy',$listy)->assign('order_num',I('order_num'))->assign('infoy',$infoy)->assign('infon',$infon)->display();
    }

    //沟通
    //pages 跳转的页面参数，用于区分甲方、乙方
    public function talking(){
        $id = I('id');
        $table = I('table');
        if($table == 'send_agreement'){
            //乙方找甲方聊天沟通。。。
            $where['id'] = $id;
            $info = M($table)->where($where)->find();
            $info['avatar'] = M($_SESSION['role'])->where('id='.$_SESSION['user']['id'])->getField('avatar');
            $status['partya_id'] = $info['partya_id'];
            $status['partya_role'] = $info['partya_role'];
            $status['partyb_id'] = $_SESSION['user']['id'];
            $status['partyb_role'] = $_SESSION['role'];   
            $obj = M('talking')->where($status)->field('id,content')->find();
            if($obj){
                $this->assign('talking_id',$obj['id']);
                $this->assign('old_cont',$obj['content']);
            }
        //添加消息start
            $msg_name = M($_SESSION['role'])->where('id='.$_SESSION['user']['id'])->getField("name");
            $message['partya_id'] = $info['partya_id'];
            $message['partya_role'] = $info['partya_role'];
            $message['partyb_id'] = $_SESSION['user']['id'];
            $message['partyb_role'] = $_SESSION['role'];
            $message['create_time'] = date("Y-m-d H:i:s");
            $message['status'] = 2;
            $message['msg_content'] = $msg_name."有消息回复给您哦";
            $msg = M('message')->add($message);
        //添加消息end
        //微信推送调用start
            $wx_res = M($info['partya_role'])->where("id =".$info['partya_id'])->getField('openid');
            if($wx_res){
                $value = $msg_name."有消息回复给您哦";
                $this->sendCustom($wx_res,$value);
            }
        //微信推送调用end
            $this->assign('info',$info)->display(I('pages'));
        }else{
            //甲方找乙方聊天沟通。。。
            $order_num = I('order_num');
            $data = M('send_agreement')->where("order_num ='".$order_num."' and status = 1")->field('id',true)->find();
            $data['partyb_id'] = $id;
            $data['partyb_role'] = $table;
            $list = M($table)->where("id =".$id)->find();
            $list['avatar'] = M($_SESSION['role'])->where('id='.$_SESSION['user']['id'])->getField('avatar');
            $data['partyb_name'] = $list['name'];
            $data['partyb_mobile'] = $list['mobile'];
            $data['order_num'] = $order_num;
            $data['status'] = 2;
            //需要写判断是否有该角色的该订单的记录，如果有，只需要保存原记录，如果没有，创建新记录
            $res = M('send_agreement')->where("order_num ='".$order_num."'  and partyb_id ='".$id."' and partyb_role ='".$table."'")->getField('id');
            if(!$res){
                $res = M('send_agreement')->add($data);
            }
            $where['status'] = 2;
            $where['status2_time'] = date("Y-m-d H:i:s");
            $where['update_time'] = date("Y-m-d H:i:s");
            $result = M('indent')->where("order_num ='".$order_num."'")->save($where);
            if($result !== false){
                $status['partya_id'] = $_SESSION['user']['id'];
                $status['partya_role'] = $_SESSION['role'];
                $status['partyb_id'] = $id;
                $status['partyb_role'] = $table;
                $messages = M('message')->add($tatus);
                $re_id = M('talking')->where($status)->field('id,content')->find();
                if($re_id){
                    $talking_id = $re_id['id'];
                    $this->assign("old_cont",$re_id['content']);
                }else{
                    $status['create_time'] = date("Y-m-d H:i:s");
                    $talking_id = M('talking')->add($status);
                    $this->assign("old_cont","");
                }
                if($talking_id){
                    $this->assign('talking_id',$talking_id);
                }
            //添加消息start
                $msg_name = M($_SESSION['role'])->where('id='.$_SESSION['user']['id'])->getField("name");
                $message['partya_id'] = $_SESSION['user']['id'];
                $message['partya_role'] = $_SESSION['role'];
                $message['partyb_id'] = $id;
                $message['partyb_role'] = $table;
                $message['create_time'] = date("Y-m-d H:i:s");
                $message['status'] = 1;
                $message['msg_content'] = $msg_name."有派单找您，快去接单吧";
                $msg = M('message')->add($message);
            //添加消息end
            //微信推送调用start
                $wx_res = M($table)->where("id =".$id)->getField('openid');
                if($wx_res){
                    $value = $msg_name."有派单找您，快去接单吧";
                    $this->sendCustom($wx_res,$value);
                }
            //微信推送调用end
            }
            $this->assign("partyb_id",$id)->assign("partyb_role",$table);
            $this->assign('info',$list)->assign('send_id',$res)->display(I('pages'));
        }   
    }
    //查看详情
    //pages 跳转的页面参数，用于区分甲方、乙方
    public function details(){
        $id = I('id');
        $table = I('table');
        $list = M($table)->where("id =".$id)->find();
        if($table == 'send_agreement'){
            //乙方查看甲方发布的订单详情信息
            $list['machine_type'] = M('device_type')->where("id =".$list['machine_type'])->getField("name");
            $this->assign('list',$list)->display(I('pages'));
        }else{
            //甲方查看乙方的详情信息
            if($table == 'repair_user'){
                $arr = C('IDENTITY');
                $arr1 = explode(',', $list['identity']);
                $list['identity_name'] = "";
                for($i=0;$i<count($arr1);$i++){
                    $list['identity_name'] .= $arr[$arr1[$i]].", ";
                }
                $list['identity_name'] = substr($list['identity_name'],0,-2);
            }
            $arr = explode(',', $list['adept_device']);
            $list['adept_device_name'] = "";
            for($i = 0;$i<count($arr);$i++){
                $list['adept_device_name'] .= M('device_type')->where('id ='.$arr[$i])->getField('name').", ";
            }
            $list['adept_device_name'] = substr($list['adept_device_name'],0,-2);
            $this->assign("list",$list)->assign('table',$table)->display(I('pages'));
        }
    }
    //派工协议查看或编辑
    //type  跳转的页面参数，用于区分甲方、乙方
    public function  job_agreement(){
        $send_id = I('send_id');
        $data = M('send_agreement')->where('id ='.$send_id)->find();
        $this->assign('data',$data)->assign('send_id',$send_id)->display(I('type'));   
    }
    //立即评价
    public function evaluate(){
        if(IS_POST){
            $info = M('indent')->where("order_num ='".I('order_num')."'")->field('partya_id,partya_role,partyb_id,partyb_role,money,tui_money')->find();
            $info['partya_name'] = M($info['partya_role'])->where('id ='.$info['partya_id'])->getField('name'); 
            $info['partya_mobile'] = M($info['partya_role'])->where('id ='.$info['partya_id'])->getField('mobile'); 
            $data = array_merge($info,I('post.'));
            $arr = C('DISAGREE');
            $data['disagree'] = $arr[$data['disagree']];
            $data['order_num'] = I('order_num');
            $data['create_time'] = date("Y-m-d H:i:s");
            $res = M('satisfaction')->add($data);
            if($res){
                $status['status'] = 9;
                // $status['counts'] = 1;
                $status['status9_time'] = date("Y-m-d H:i:s");
                $result = M('indent')->where("order_num ='".I('order_num')."'")->save($status);
                if($result !== false){
                //添加消息start
                    $msg_name = M($info['partya_role'])->where('id='.$info['partya_id'])->getField("name");
                    $message['partya_id'] = $info['partya_id'];
                    $message['partya_role'] = $info['partya_role'];
                    $message['partyb_id'] = $info['partyb_id'];
                    $message['partyb_role'] = $info['partyb_role'];
                    $message['create_time'] = date("Y-m-d H:i:s");
                    $message['status'] = 1;
                    $message['msg_content'] = $msg_name."有给您评价哦，快去看看吧";
                    $msg = M('message')->add($message);
                //添加消息end
                //微信推送调用start
                    $wx_res = M($info['partyb_role'])->where("id =".$info['partyb_id'])->getField('openid');
                    if($wx_res){
                        $value = $msg_name."有给您评价哦，快去看看吧";
                        $this->sendCustom($wx_res,$value);
                    }
                //微信推送调用end
                //将钱存到我的余额里status
                    $tixian['uid'] = $info['partyb_id'];
                    $tixian['role'] = $info['partyb_role'];
                    $tixian['balance'] = $info['money']-$info['tui_money'];
                    $bank = M('bank_card')->where("uid =".$info['partyb_id']." and role ='".$info['partyb_role']."'")->field('id,balance')->find();
                    if($bank){
                        $tixian['balance'] = $bank['balance']+$tixian['balance'];
                        $res = M('bank_card')->where("id =".$bank['id'])->save($tixian);
                    }
                //将钱存到我的余额里end
                    $this->display("evaluate_success");
                }else{
                    //$this->display("evaluate_error");
                    //页面还未设计
                }
            }else{
                //$this->display("evaluate_error");
                //页面还未设计
            }
        }else{ 
            $where['id'] = I('partyb_id');
            $table = I('partyb_role');
            $partyb_name = M($table)->where($where)->getField('name');
            $this->assign('partyb_name',$partyb_name)->assign('order_num',I('order_num'))->display();
        }
        
    }
    //甲方确认协议
    public function subpartya(){
        $data = I('post.');
        $data['status'] = 3;
        $res = M('send_agreement')->where('id ='.I('send_id'))->save($data);
        $order_num = M('send_agreement')->where('id ='.I('send_id'))->getField('order_num');
        if($res !== false){
            $where['status'] = 12;
            $result = M('indent')->where("order_num='".$order_num."'")->save($where); 
            if($result !== false){
            //添加消息start
                $role_arr = M('send_agreement')->where('id ='.I('send_id'))->field('partyb_id,partyb_role,partya_id,partya_role')->find();
                $msg_name = M($role_arr['partya_role'])->where('id='.$role_arr['partya_id'])->getField("name");
                $message['partya_id'] = $role_arr['partya_id'];
                $message['partya_role'] = $role_arr['partya_role'];
                $message['partyb_id'] = $role_arr['partyb_id'];
                $message['partyb_role'] = $role_arr['partyb_role'];
                $message['create_time'] = date("Y-m-d H:i:s");
                $message['status'] = 1;
                $message['msg_content'] = $msg_name."跟您确认协议了！注意查看哦";
                $msg = M('message')->add($message);
            //添加消息end
            //微信推送调用start
                $wx_res = M($role_arr['partyb_role'])->where("id =".$role_arr['partyb_id'])->getField('openid');
                if($wx_res){
                    $value = $msg_name."跟您确认协议了！注意查看哦";
                    $this->sendCustom($wx_res,$value);
                }
            //微信推送调用end
                $this->success('提交成功，正等待乙方确认',U('Order/index',array('complete'=>2,'pages'=>'indexa')));
            }else{
                $this->error('提交失败',U('Order/index',array('pages'=>'indexa')));
            } 
        }else{
            $this->error('提交失败',U('Order/index',array('pages'=>'indexa')));
        }
    }
    //乙方确认协议 | 乙方取消协议
    //依据sub 进行判断 sub ='确认': 乙方确认协议 sub = '取消': 乙方取消协议
    public function subpartyb(){
        if(I('sub') == '确认'){
            $where['id'] = I('send_id');
            $data['finish_time'] = date('Y-m-d H:i:s');
            $data['status'] = 4;
            $data['open_invoice'] = I('open_invoice');
            $data['invoice_title'] = I('invoice_title');
            $data['invoice_comment'] = I('invoice_comment');
            $res = M('send_agreement')->where($where)->save($data);
            if($res !== false){
                $status['status'] = 3;
                // $status['counts'] = 1;
                $status['partyb_role'] = I('partyb_role');
                $status['partyb_id'] = I('partyb_id');
                $status['money'] = I('money');
                $status['send_agreement_id'] = I('send_id');
                $status['update_time'] = date("Y-m-d H:i:s");
                $status['status3_time'] = date("Y-m-d H:i:s");
                $result = M('indent')->where("order_num ='".I('order_num')."'")->save($status);
                if($result !== false){
                    $del['order_num'] = I('order_num');
                    $del['status'] = array('not in','4');
                    $delete = M('send_agreement')->where($del)->delete();
                //添加消息 start   
                    $msg_arr = M('indent')->where("order_num ='".I('order_num')."'")->field('partya_id,partya_role')->find();
                    $msg_name = M(I('partyb_role'))->where('id='.I('partyb_id'))->getField("name");
                    $message['partya_id'] = $msg_arr['partya_id'];
                    $message['partya_role'] = $msg_arr['partya_role'];
                    $message['partyb_id'] = I('partyb_id');
                    $message['partyb_role'] = I('partyb_role');
                    $message['create_time'] = date("Y-m-d H:i:s");
                    $message['status'] = 2;
                    $message['msg_content'] = $msg_name."接收并确认了您的订单！注意查看哦";
                    $msg = M('message')->add($message);
                //添加消息end
                //微信推送调用start
                    $wx_res = M($msg_arr['partya_role'])->where("id =".$msg_arr['partya_id'])->getField('openid');
                    if($wx_res){
                        $value = $msg_name."接收并确认了您的订单！注意查看哦";
                        $this->sendCustom($wx_res,$value);
                    }
                //微信推送调用end
                    $this->success('确认成功，订单已形成',U('Order/index',array('complete'=>2,'pages'=>'indexb')));
                }else{
                    $this->error('确认失败',U('Order/index',array('pages'=>'indexb')));
                }
            }else{
                $this->error('确认失败',U('Order/index',array('pages'=>'indexb')));
            }
        }elseif(I('sub') == '取消'){
            $where['id'] = I('send_id');
            $res = M('send_agreement')->where($where)->delete();
            if($res){
                $data['status'] = 2;
                // $data['counts'] = 1;
                $result = M('indent')->where("order_num ='".I('order_num')."'")->save($data);
                if($result !== false){
                //添加消息 start   
                    $msg_arr = M('indent')->where("order_num ='".I('order_num')."'")->field('partya_id,partya_role')->find();
                    $msg_name = M($_SESSION['role'])->where('id='.$_SESSION['user']['id'])->getField("name");
                    $message['partya_id'] = $msg_arr['partya_id'];
                    $message['partya_role'] = $msg_arr['partya_role'];
                    $message['partyb_id'] = $_SESSION['user']['id'];
                    $message['partyb_role'] = $_SESSION['role'];
                    $message['create_time'] = date("Y-m-d H:i:s");
                    $message['status'] = 2;
                    $message['msg_content'] = $msg_name."取消了您的订单，请重新派单吧";
                    $msg = M('message')->add($message);
                //添加消息end
                //微信推送调用start
                    $wx_res = M($msg_arr['partya_role'])->where("id =".$msg_arr['partya_id'])->getField('openid');
                    if($wx_res){
                        $value = $msg_name."取消了您的订单，请重新派单吧";
                        $this->sendCustom($wx_res,$value);
                    }
                //微信推送调用end
                    $this->success('已取消订单',U('Order/index',array('pages'=>'indexb')));
                }else{
                    $this->error('取消失败',U('Order/index',array('pages'=>'indexb')));
                }
            }else{
                $this->error('取消失败1',U('Order/index',array('pages'=>'indexb')));
            }
        }
    }

    //甲方确认乙方到现场
    public function sub5(){
        if(IS_AJAX){
            $data['status'] = 5;
            // $data['counts'] = 1;
            $data['status5_time'] = date("Y-m-d H:i:s");
            $res = M('indent')->where("order_num='".I('order_num')."'")->save($data);
            if($res !== false){
                //添加消息 start   
                    $msg_arr = M('indent')->where("order_num ='".I('order_num')."'")->field('partya_id,partya_role,partyb_id,partyb_role')->find();
                    $msg_name = M($msg_arr['partya_role'])->where('id='.$msg_arr['partya_id'])->getField("name");
                    $message['partya_id'] = $msg_arr['partya_id'];
                    $message['partya_role'] = $msg_arr['partya_role'];
                    $message['partyb_id'] = $msg_arr['partyb_id'];
                    $message['partyb_role'] = $msg_arr['partyb_role'];
                    $message['create_time'] = date("Y-m-d H:i:s");
                    $message['status'] = 1;
                    $message['msg_content'] = $msg_name."已确认了您的到场，开始维修吧";
                    $msg = M('message')->add($message);
                //添加消息end
                //微信推送调用start
                    $wx_res = M($msg_arr['partyb_role'])->where("id =".$msg_arr['partyb_id'])->getField('openid');
                    if($wx_res){
                        $value = $msg_name."已确认了您的到场，开始维修吧";
                        $this->sendCustom($wx_res,$value);
                    }
                //微信推送调用end
                $this->ajaxReturn(json_encode(array('code'=>200,'msg'=>'确认维修方到场')));
            }else{
                $this->ajaxReturn(json_encode(array('code'=>201,'msg'=>'出错')));
            }
        }
    }

    //甲方确认乙方完成
    public function sub6(){
        if(IS_AJAX){
            if(I('type') == 1){
                $data['status'] = 6;
                // $data['counts'] = 1;
                $data['status6_time'] = date("Y-m-d H:i:s");
                $str1 = "确认维修完成";
                $str2 = "出错";
            }else{
                $data['status'] = 10;
                // $data['counts'] = 1;
                $data['if_complete'] = 1;
                $data['status10_time'] = date("Y-m-d H:i:s");
                $str1 = "确认维修未完成";
                $str2 = "出错";
            }
            $res = M('indent')->where("order_num='".I('order_num')."'")->save($data);
            if($res !== false){
                //添加消息 start   
                    $msg_arr = M('indent')->where("order_num ='".I('order_num')."'")->field('partya_id,partya_role,partyb_id,partyb_role')->find();
                    $msg_name = M($msg_arr['partya_role'])->where('id='.$msg_arr['partya_id'])->getField("name");
                    $message['partya_id'] = $msg_arr['partya_id'];
                    $message['partya_role'] = $msg_arr['partya_role'];
                    $message['partyb_id'] = $msg_arr['partyb_id'];
                    $message['partyb_role'] = $msg_arr['partyb_role'];
                    $message['create_time'] = date("Y-m-d H:i:s");
                    $message['status'] = 1;
                    $message['msg_content'] = $msg_name."已确认了您的维修完成情况，注意查看吧";
                    $msg = M('message')->add($message);
                //添加消息end
                //微信推送调用start
                    $wx_res = M($msg_arr['partyb_role'])->where("id =".$msg_arr['partyb_id'])->getField('openid');
                    if($wx_res){
                        $value = $msg_name."已确认了您的维修完成情况，注意查看吧";
                        $this->sendCustom($wx_res,$value);
                    }
                //微信推送调用end
                $this->ajaxReturn(json_encode(array('code'=>200,'msg'=>$str1)));
            }else{
                $this->ajaxReturn(json_encode(array('code'=>201,'msg'=>$str2)));
            }
        }
    }

    //甲方申请退款
    public function sub10(){
        if(IS_AJAX){
            $data['status'] = 11;
            // $data['counts'] = 1;
            $data['tui_money'] = I('tui_money');
            $data['status11_time'] = date("Y-m-d H:i:s");
            // $num = M('indent')->where("order_num='".I('order_num')."'")->getField('money');
            $res = M('indent')->where("order_num='".I('order_num')."'")->save($data);
            if($res !== false){
                //添加消息 start   
                    $msg_arr = M('indent')->where("order_num ='".I('order_num')."'")->field('partya_id,partya_role,partyb_id,partyb_role')->find();
                    $msg_name = M($msg_arr['partya_role'])->where('id='.$msg_arr['partya_id'])->getField("name");
                    $message['partya_id'] = $msg_arr['partya_id'];
                    $message['partya_role'] = $msg_arr['partya_role'];
                    $message['partyb_id'] = $msg_arr['partyb_id'];
                    $message['partyb_role'] = $msg_arr['partyb_role'];
                    $message['create_time'] = date("Y-m-d H:i:s");
                    $message['status'] = 1;
                    $message['msg_content'] = $msg_name."已向平台申请了退款，注意查看吧";
                    $msg = M('message')->add($message);
                //添加消息end
                //微信推送调用start
                    $wx_res = M($msg_arr['partyb_role'])->where("id =".$msg_arr['partyb_id'])->getField('openid');
                    if($wx_res){
                        $value = $msg_name."已向平台申请了退款，注意查看吧";
                        $this->sendCustom($wx_res,$value);
                    }
                //微信推送调用end
                $this->ajaxReturn(json_encode(array('code'=>200,'msg'=>'正在受理中')));
            }else{
                $this->ajaxReturn(json_encode(array('code'=>201,'msg'=>'出错')));
            }
        }
    }
    //乙方确认到场
    public function sub14(){ 
        if(IS_AJAX){
            $data['status'] = 14;
            // $data['counts'] = 1;
            $data['addrs'] = I('addrs');
            $res = M('indent')->where("order_num='".I('order_num')."'")->save($data);
            if($res !== false){
            //添加消息 start   
                $msg_arr = M('indent')->where("order_num ='".I('order_num')."'")->field('partya_id,partya_role,partyb_id,partyb_role')->find();
                $msg_name = M($msg_arr['partyb_role'])->where('id='.$msg_arr['partyb_id'])->getField("name");
                $message['partya_id'] = $msg_arr['partya_id'];
                $message['partya_role'] = $msg_arr['partya_role'];
                $message['partyb_id'] = $msg_arr['partyb_id'];
                $message['partyb_role'] = $msg_arr['partyb_role'];
                $message['create_time'] = date("Y-m-d H:i:s");
                $message['status'] = 2;
                $message['msg_content'] = $msg_name."向您发送确认到场请求，注意查看吧";
                $msg = M('message')->add($message);
            //添加消息end
            //微信推送调用start
                $wx_res = M($msg_arr['partya_role'])->where("id =".$msg_arr['partya_id'])->getField('openid');
                if($wx_res){
                    $value = $msg_name."向您发送确认到场请求，注意查看吧";
                    $this->sendCustom($wx_res,$value);
                }
            //微信推送调用end
                $this->ajaxReturn(json_encode(array('code'=>200,'msg'=>'等到确认中')));
            }else{
                $this->ajaxReturn(json_encode(array('code'=>201,'msg'=>'出错')));
            }

        }
    }
    /*write by mike 消息提醒 或 清除消息提醒
    //乙方实时查看是否有新消息提醒（15s查询一次）
    public function search_jd(){
        $where['partyb_id'] = $_SESSION['user']['id'];
        $where['partyb_role'] = session('role');
        $where['counts'] = 1;
        $count = M('send_agreement')->where($where)->count();
        if($count){
            $this->ajaxReturn(json_encode(array('code'=>200)));
        }else{
             $this->ajaxReturn(json_encode(array('code'=>201)));
        } 
    }
    //乙方进入接单时，清空新消息提醒
    public function jd_goback(){
        $where['partyb_id'] = $_SESSION['user']['id'];
        $where['partyb_role'] = session('role');
        $data['counts'] = 2;
        $res = M('send_agreement')->where($where)->save($data);
        if($res !== false){
            $this->ajaxReturn(json_encode(array('code'=>200)));
        }else{
             $this->ajaxReturn(json_encode(array('code'=>201)));
        }
    }
    //未完成订单的新消息提醒
    public function search_unfinish(){
        if(IS_AJAX){
            $where['counts'] = 1;
            $where['order_num'] = I('order_num');
            $count = M('indent')->where($where)->count();
            if($count){
                if($_SESSION['role'] == 'repair_user' || $_SESSION['role'] == 'repair_agency'){
                    $where['partyb_id'] = $_SESSION['user']['id'];
                    $where['partyb_role'] = session('role');
                }elseif($_SESSION['role'] == 'hospital' || $_SESSION['role'] == 'device_firms'){
                    $where['partya_id'] = $_SESSION['user']['id'];
                    $where['partya_role'] = session('role');
                }
                $res = M('indent')->where($where)->getField('status');
                if($res != $status && $res != 9){
                    $this->ajaxReturn(json_encode(array('code'=>200,'ress'=>$res)));
                }else if($res != $status && $res == 9){
                    $this->ajaxReturn(json_encode(array('code'=>201)));
                }else{
                    $this->ajaxReturn(json_encode(array('code'=>202)));
                }
            }else{
                $this->ajaxReturn(json_encode(array('code'=>202)));
            }
        }
    }
    //当进入查看详情时，清空新消息提醒
    public function ckxq_mike(){
        if($_SESSION['role'] == 'repair_user' || $_SESSION['role'] == 'repair_agency'){
            $where['partyb_id'] = $_SESSION['user']['id'];
            $where['partyb_role'] = session('role');
        }elseif($_SESSION['role'] == 'hospital' || $_SESSION['role'] == 'device_firms'){
            $where['partya_id'] = $_SESSION['user']['id'];
            $where['partya_role'] = session('role');
        }
        $where['order_num'] = I('order_num');
        $data['counts'] = 2;
        $res = M('indent')->where($where)->save($data);
        if($res !== false){
            $this->ajaxReturn(json_encode(array('code'=>200)));
        }else{
             $this->ajaxReturn(json_encode(array('code'=>201)));
        }
    }
    */
    //保存聊天记录
    public function save_talk(){
        if(IS_AJAX){
            $id = I('id');
            $data['update_time'] = date("Y-m-d H:i:s");
            $old_cont = M('talking')->where("id =".$id)->getField('content');
            $data['content'] = $old_cont.I('content');
            $res = M('talking')->where("id=".$id)->save($data);
            if($res){
                $this->ajaxReturn(array("code"=>200));
            }else{
                $this->ajaxReturn(array("code"=>201));
            }

        }
    }
    //获取聊天记录
    public function get_talk(){
        if(IS_AJAX){
            $id = I('id');
            $cont = M('talking')->where("id =".$id)->getField('content');
            if($cont){
                $this->ajaxReturn(array("code"=>200,'cont'=>$cont));
            }else{
                $this->ajaxReturn(array("code"=>201));
            }
        }
    }

    //b_sub5
    public function b_sub5(){
        if(IS_AJAX){
            if(I('type') == 1){
                $str1 = "确认维修完成";
            }else{
                $str1 = "确认维修未完成";
            }
        //添加消息 start   
            $msg_arr = M('indent')->where("order_num ='".I('order_num')."'")->field('partya_id,partya_role,partyb_id,partyb_role')->find();
            $msg_name = M($msg_arr['partyb_role'])->where('id='.$msg_arr['partyb_id'])->getField("name");
            $message['partya_id'] = $msg_arr['partya_id'];
            $message['partya_role'] = $msg_arr['partya_role'];
            $message['partyb_id'] = $msg_arr['partyb_id'];
            $message['partyb_role'] = $msg_arr['partyb_role'];
            $message['create_time'] = date("Y-m-d H:i:s");
            $message['status'] = 2;
            $message['msg_content'] = $msg_name."发布了他的维修完成情况，注意查看吧";
            $msg = M('message')->add($message);
        //添加消息end
        //微信推送调用start
            $wx_res = M($msg_arr['partyb_role'])->where("id =".$msg_arr['partyb_id'])->getField('openid');
            if($wx_res){
                $value = $msg_name."发布了他的维修完成情况，注意查看吧";
                $this->sendCustom($wx_res,$value);
            }
        //微信推送调用end
            $this->ajaxReturn(json_encode(array('code'=>200,'msg'=>$str1))); 
        }
    }
    private function get_php_file($filename) {
		return trim(substr(file_get_contents($filename), 15));
	}
	private function set_php_file($filename, $content) {
		$fp = fopen($filename, "w");
		fwrite($fp, "<?php exit();?>" . $content);
		fclose($fp);
	}

    /**
     *功能：微信推送
     */
    public function sendCustom($openid,$value,$type = 'text'){
        $jssdk = new Jssdk(C('APP_ID'), C('APP_SECRET'));
        $access_token = $jssdk->setAccessToken();
        $val = $value;
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
        if ($type == 'text') {
            $data = '{
                "touser":"' . $openid . '",
                "msgtype":"text",
                "text":
                {
                     "content":"' . $val . '"
                }
            }';
        }; 
        
        $result=$this->httpPost($url, $data);
    }
    /**
     *功能：微信推送
     */
    public function httpPost($url, $data){        
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            return curl_exec($ch);
    }

    //添加支付凭证
    public function mike_zhifu(){
        if(IS_AJAX){
            $order_num = I("order_num");
            $data['payment'] = I('payment');
            $data['pay_code'] = 3;
            $data['status'] = 4;
            $data['status4_time'] = date("Y-m-d H:i:s");
            $res = M('indent')->where("order_num ='".$order_num."'" )->save($data);
            if($res !== false){
                echo 200;
            }else{
                echo 201;
            }
        }
    }
}